package com.saishi.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.util.List;

@WebServlet(value = "/Exc")
public class ExcelServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      doPost(request,response);
    }
    //电脑文件上传到服务器文件
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        DiskFileItemFactory disk=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(disk);
        upload.setHeaderEncoding("UTF-8"); // 中文处理
        // 项目的发布位置
        String apppath = request.getServletContext().getRealPath("/doc");
        System.out.println("上传位置="+apppath);
        try {
            List<FileItem> list = upload.parseRequest(request);
            //存盘 d:/xxxx/xxx/doc   /abc.xls
            for (FileItem fi : list) {
                if( fi.isFormField()){
                    //文本框
                    String name = fi.getFieldName();
                    String value = fi.getString("utf-8");
                    System.out.println( name+value);
                }else{
                    //文件
                    File file = new File(apppath+"/"+fi.getName());
                    fi.write(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
